package com.apesay.agent;

import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * ClassName:PluginsLoader
 * Reason:	 
 * Date:     2017/11/7 10:16
 *
 * @author sid
 */
public class PluginsLoader {
    static String dirPath = "E:\\workspace_share";
    static String jarPath = dirPath+"\\plugins\\target\\;"+dirPath+"\\plugins2\\target\\;"+dirPath+"\\plugins3\\target\\";
    static URL[] urls;
    static ArrayList<URL> urlArrayList = new ArrayList<URL>();

    static {
        try {

            dirPath = System.getProperty("user.dir");
            System.out.println("PluginsLoader find home dir is :"+dirPath);
            jarPath = dirPath+"\\plugins\\target\\;"+dirPath+"\\plugins2\\target\\;"+dirPath+"\\plugins3\\target\\";
            
            String[] jarPaths = jarPath.split(";");
            for (String path:jarPaths) {
                File file = new File(path);
                File[] jars = file.listFiles( new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.endsWith(".jar");
                    }
                });
                if (null==jars||jars.length==0)
                    continue;
                for (int i = 0; i < jars.length; i++) {
                    try {
                        urlArrayList.add(jars[i].toURI().toURL());
                    } catch (MalformedURLException e) {
                        throw new RuntimeException("Fail to load plugin jars", e);
                    }
                }
            }
            urls = urlArrayList.toArray(new URL[urlArrayList.size()]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static <T> List<T> load(Class<T> serviceType) {
        URLClassLoader classLoader = createPluginClassLoader(urls, ClassLoader.getSystemClassLoader());
        return load(serviceType, classLoader);
    }

    private static PluginLoaderClassLoader createPluginClassLoader(final URL[] urls, final ClassLoader parent) {
        return new PluginLoaderClassLoader(urls, parent);
    }

    public static <T> List<T> load(Class<T> serviceType, ClassLoader classLoader) {
        ServiceLoader<T> serviceLoader = ServiceLoader.load(serviceType, classLoader);

        List<T> plugins = new ArrayList<T>();
        for (T plugin : serviceLoader) {
            plugins.add(plugin);
        }

        return plugins;
    }
}
